package ethrpc

import (
	"context"
	"github.com/ethereum/go-ethereum/common"
	"github.com/ethereum/go-ethereum/core/types"
	"github.com/ethereum/go-ethereum/ethclient"
	"math/big"
)

type EthClientWrapper struct {
	url       string
	ethClient *ethclient.Client
}

func New(url string) *EthClientWrapper {
	return &EthClientWrapper{
		url: url,
	}
}

func (ecw *EthClientWrapper) Dial() error {
	client, err := ethclient.Dial(ecw.url)
	if err != nil {
		return err
	}
	ecw.ethClient = client

	return nil
}

func (ecw *EthClientWrapper) Close() {
	ecw.ethClient.Close()
}

func (ecw *EthClientWrapper) GetLatestBlock(ctx context.Context) (*types.Block, error) {
	num, err := ecw.ethClient.BlockNumber(ctx)
	if err != nil {
		return nil, err
	}

	return ecw.ethClient.BlockByNumber(ctx, big.NewInt(int64(num)))
}

func (ecw *EthClientWrapper) GetBlockByNumber(ctx context.Context, number int64) (*types.Block, error) {

	return ecw.ethClient.BlockByNumber(ctx, big.NewInt(number))
}

func (ecw *EthClientWrapper) PendingTransactionCount(ctx context.Context) (uint, error) {

	return ecw.ethClient.PendingTransactionCount(ctx)
}

func (ecw *EthClientWrapper) GetTransactions(ctx context.Context, blockNumber int64) (types.Transactions, error) {
	block, err := ecw.ethClient.BlockByNumber(ctx, big.NewInt(int64(blockNumber)))
	if err != nil {
		return nil, err
	}
	return block.Transactions(), nil
}

func (ecw *EthClientWrapper) GetTransactionByHash(ctx context.Context, hash string) (*types.Transaction, bool, error) {
	h := common.HexToHash(hash)
	return ecw.ethClient.TransactionByHash(ctx, h)
}
